import React, { createContext, useContext, useState, useEffect } from 'react';

const ChallengeContext = createContext();

export function ChallengeProvider({ children }) {
  const [userChallenges, setUserChallenges] = useState(() => {
    const saved = localStorage.getItem('userChallenges');
    return saved ? JSON.parse(saved) : [];
  });

  const [userPoints, setUserPoints] = useState(() => {
    const saved = localStorage.getItem('userPoints');
    return saved ? parseInt(saved) : 0;
  });

  useEffect(() => {
    localStorage.setItem('userChallenges', JSON.stringify(userChallenges));
    localStorage.setItem('userPoints', userPoints.toString());
  }, [userChallenges, userPoints]);

  const joinChallenge = (challenge) => {
    console.log('加入挑战:', challenge); // 调试日志
    
    // 检查是否已经参与
    if (userChallenges.some(c => c.id === challenge.id)) {
      console.log('已经参与过此挑战'); // 调试日志
      return false;
    }

    // 添加新挑战
    const newChallenge = {
      id: challenge.id,
      title: challenge.title,
      points: challenge.points,
      startDate: new Date(),
      progress: 0,
      completedTasks: [],
      tasks: challenge.tasks
    };

    console.log('添加新挑战:', newChallenge); // 调试日志
    setUserChallenges(prev => [...prev, newChallenge]);
    return true;
  };

  const updateProgress = (challengeId, progress, completedTasks) => {
    setUserChallenges(userChallenges.map(c => {
      if (c.id === challengeId) {
        return {
          ...c,
          progress,
          completedTasks,
          lastUpdated: new Date()
        };
      }
      return c;
    }));

    if (progress === 100) {
      const challenge = userChallenges.find(c => c.id === challengeId);
      if (challenge && !challenge.completed) {
        setUserPoints(points => points + challenge.points);
      }
    }
  };

  return (
    <ChallengeContext.Provider value={{
      userChallenges,
      userPoints,
      joinChallenge,
      updateProgress
    }}>
      {children}
    </ChallengeContext.Provider>
  );
}

export function useChallenges() {
  return useContext(ChallengeContext);
}